<template>
  <div class="FKLSalaryIndex">
    <img id="fkl_logo" src="//12200710.s21i.faiusr.com/4/ABUIABAEGAAgmoOg4gUo4fmO8AIw2AM4PQ.png" alt="flk_logo">
    <br>

    <el-upload
        action="8.144.172.143"
        :on-change="handleChange"
        :on-exceed="handleExceed"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :file-list="fileListUpload"
        :limit="limitUpload"
        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        :auto-upload="false">
      <el-button size="small" type="primary" icon="el-icon-upload2">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只 能 上 传 xlsx / xls 文 件</div>
    </el-upload>
    <p></p>
    <el-link target="_blank" :href="demoFileUrl" :underline="false" >
      <el-button  size="small" icon="el-icon-document" >样例文件</el-button>
    </el-link>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item class="x-el-form-item-label" label="姓名">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item class="x-el-form-item-label" label="月薪">
              <span>{{ props.row.monthly_salary }} 元</span>
            </el-form-item>
            <el-form-item class="x-el-form-item-label" label="事假">
              <span>{{ props.row.personal_leave_day.length }} 天  </span>
            </el-form-item>
            <el-form-item class="x-el-form-item-label" label="病假">
              <span>{{ props.row.sick_leave_day.length }} 天 </span>
            </el-form-item>
            <!--            入职计算-->
            <el-form-item :inline="true">
              <el-checkbox label="本月入职" v-model="props.row.is_join_this_month"
                           :disabled="props.row.is_quit_this_month"
                           @change="calculateSalarySingle(props.row)"></el-checkbox>
              <span v-show="props.row.is_join_this_month && !props.row.is_join_certain">
                <el-date-picker size="medium" class="margin-right-10" type="date" v-model="props.row.join_date"
                                placeholder="选择一个入职日期"
                                format="yyyy-MM-dd" value-format="yyyyMMdd"></el-date-picker>
                <el-button :loading="props.row.join_loading" size="medium"
                           @click='certainJoinOrQuitDate(props.row,"join")' type="primary"
                           :disabled="props.row.join_date==null">确定</el-button>
              </span>
              <span v-show="props.row.is_join_certain && props.row.is_join_this_month">
                <el-button size="medium">入职时间：{{ props.row.join_date }} , 当月工作天数：{{
                    props.row.work_days_join
                  }} 天</el-button>
                <el-button size="medium" type="warning" @click="updateJoinDate(props.row)">修改</el-button>
              </span>
            </el-form-item>
            <!--            离职计算-->
            <el-form-item>
              <el-checkbox label="本月离职" v-model="props.row.is_quit_this_month"
                           :disabled="props.row.is_join_this_month"
                           @change="calculateSalarySingle(props.row)"></el-checkbox>
              <span v-show="props.row.is_quit_this_month && !props.row.is_quit_certain">
                <el-date-picker size="medium" class="margin-right-10" type="date" v-model="props.row.quit_date"
                                placeholder="选择一个离职日期"
                                format="yyyy-MM-dd" value-format="yyyyMMdd"></el-date-picker>
                <el-button :loading="props.row.quit_loading" size="medium"
                           @click='certainJoinOrQuitDate(props.row,"quit")' type="primary"
                           :disabled="props.row.quit_date==null">确定</el-button>
              </span>
              <span v-show="props.row.is_quit_certain && props.row.is_quit_this_month">
                <el-button size="medium">离职时间：{{
                    props.row.quit_date
                  }} , 当月工作天数：{{ props.row.work_days_quit }} 天</el-button>
                <el-button size="medium" type="success" @click="updateQuitDate(props.row)">修改</el-button>
              </span>
            </el-form-item>
            <el-form-item class="x-el-form-item-label" label="薪水总额">
              <span>{{ props.row.total_salary }} 元</span>
              <span v-if="props.row.total_salary_log">【计算公式：{{ props.row.total_salary_log }}】</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名">
      </el-table-column>
      <el-table-column prop="monthly_salary" label="月薪">
      </el-table-column>
      <el-table-column prop="day" label="事假" width="280">
        <template slot-scope="scope">
          <el-date-picker @change="dayChange(scope.row)"
                          type="dates" v-model="scope.row.personal_leave_day" placeholder="选择一个或多个日期"
                          format="yyyy-MM-dd" value-format="yyyyMMdd"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="day" label="病假" width="280">
        <template slot-scope="scope">
          <el-date-picker @change="dayChange(scope.row)"
                          type="dates" v-model="scope.row.sick_leave_day" placeholder="选择一个或多个日期"
                          format="yyyy-MM-dd" value-format="yyyyMMdd"></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="salary_before_tax" label="税前工资"></el-table-column>
      <el-table-column prop="salary_need_tax_this_month" label="应纳税所得额（截止本月）"></el-table-column>
      <el-table-column prop="tax_paid_this_month" label="累计应纳税额（截止本月）"></el-table-column>
      <el-table-column prop="tax_need_to_pay_this_month" label="当月实际应交税额"></el-table-column>
      <el-table-column prop="total_salary" label="薪水总额(元)">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" placement="top-start">
            <span slot="content">{{ scope.row.total_salary_log }}</span>
            <el-button>{{ scope.row.total_salary }}</el-button>
          </el-tooltip>
        </template>
      </el-table-column>


      <el-table-column label="其他属性">
        <template slot-scope="scope">
          <el-button type="info" icon="el-icon-bottom-right"
                     v-if="!scope.row.is_join_this_month || !scope.row.is_join_certain" circle></el-button>
          <el-button type="warning" icon="el-icon-bottom-right"
                     v-if="scope.row.is_join_this_month && scope.row.is_join_certain" circle></el-button>
          <el-button type="success" icon="el-icon-top-right"
                     v-if="scope.row.is_quit_this_month && scope.row.is_quit_certain" circle></el-button>
          <el-button type="info" icon="el-icon-top-right"
                     v-if="!scope.row.is_quit_this_month || !scope.row.is_quit_certain" circle></el-button>
        </template>

      </el-table-column>

    </el-table>
    <p></p>
    <el-button type="success" @click="calculateTax(tableData)" icon="el-icon-magic-stick" plain>计算税额</el-button>
    <el-button type="warning" @click="exportExcel()" icon="el-icon-download" plain>导出Excel</el-button>

  </div>
</template>

<script>
import format from 'date-fns/format'
//由于静态资源配置地不是很好，所以需要在一开始导入Export2Excel.js，如果在点击按钮时再导入会出现找不到静态资源的情况
const {export_json_to_excel} = require('../utils/Export2Excel.js');
export default {
  name: "FKLSalaryIndex",
  data() {
    return {
      limitUpload: 1,
      fileListUpload: [],
      tableData: [],
      demoFileUrl: "http://8.144.172.143:8080/static/files/demo.xlsx",
      // tableData: [{
      //   name: "王小虎1",
      //   uid : 1,
      //   monthly_salary: 30000,
      //   monthly_salary_default: 30000,
      //   personal_leave_day: '',
      //   sick_leave_day: '',
      //   total_salary: '',
      //   total_salary_log: '',
      //   is_quit_this_month: false,
      //   is_join_this_month: false,
      //   is_join_certain: false,
      //   is_quit_certain: false,
      //   quit_date: '',
      //   join_date: '',
      //   work_days_quit: '',
      //   work_days_join: '',
      //   quit_loading: false,
      //   join_loading: false,
      //   salary_need_tax_last_month : 52755.56,
      //   wxyj : 1575,
      //   tax_paid_last_month : 2755.56,
      //   salary_before_tax : '',
      //   salary_need_tax_this_month : '',
      //   tax_paid_this_month : '',
      //   tax_need_to_pay_this_month : '',
      // }, {
      //   name: "王小虎2",
      //   uid : 2,
      //   monthly_salary: 30000,
      //   monthly_salary_default: 30000,
      //   personal_leave_day: '',
      //   sick_leave_day: '',
      //   total_salary: '',
      //   total_salary_log: '',
      //   is_quit_this_month: false,
      //   is_join_this_month: false,
      //   is_join_certain: false,
      //   is_quit_certain: false,
      //   quit_date: '',
      //   join_date: '',
      //   work_days_quit: '',
      //   work_days_join: '',
      //   quit_loading: false,
      //   join_loading: false,
      //   salary_need_tax_last_month : 52755.56,
      //   wxyj : 1575,
      //   tax_paid_last_month : 2755.56,
      //   salary_before_tax : '',
      //   salary_need_tax_this_month : '',
      //   tax_paid_this_month : '',
      //   tax_need_to_pay_this_month : '',
      // }],
      monthly_workdays: 21.75,
      input: '',
      is_certain: false,
      req_list: [],
    }
  },
  watch: {
    //监听tableData中
    total_salary: {
      handler(newObj, oldObj) {
        // console.log(newObj, oldObj)
      },
      deep: true
    },
  },
  mounted() {
    // this.calculateSalary();
  },
  methods: {
    calculateTax(tabledata) {
      this.req_list = [];
      tabledata.forEach(val => {
        let obj = {};
        obj.uid = val.uid;
        obj.salary_need_tax_last_month = val.salary_need_tax_last_month;
        obj.wxyj = val.wxyj;
        obj.tax_paid_last_month = val.tax_paid_last_month;
        obj.real_paid = parseFloat(val.total_salary);
        this.req_list.push(obj);
      });
      this.$post("/fkl/fklapi/v1/calTax/", this.req_list).then(res => {
        if (res.res_code === 200) {
          res.res_body.forEach(val => {
            this.tableData.forEach(val1 => {
              if (val.uid === val1.uid) {
                val1.salary_before_tax = (val.salary_before_tax).toFixed(2);
                val1.salary_need_tax_this_month = (val.salary_need_tax_this_month).toFixed(2);
                val1.tax_paid_this_month = (val.tax_paid_this_month).toFixed(2);
                val1.tax_need_to_pay_this_month = (val.tax_need_to_pay_this_month).toFixed(2);
              }
            })
          });
          this.$message({message: '计算成功', type: 'success'});
        } else {
          this.$message.error("内部错误！错误原因：" + res.res_message);
        }
      }).catch(err => {
        this.$message.error("调用错误！错误原因：" + err);
      })
    },
    certainJoinOrQuitDate(row, type) {
      let cal_date;
      if (type === 'join') {
        cal_date = row.join_date;
        row.join_loading = true;
      }
      if (type === 'quit') {
        cal_date = row.quit_date;
        row.quit_loading = true;
      }
      this.$get("/fkl/fklapi/v1/calDate?cal_date_type=" + type + "&date=" + cal_date).then((response) => {
        if (response.res_code === 200) {
          if (type === 'join') {
            row.is_join_certain = !row.is_join_certain;
            row.work_days_join = response.date_count;
            row.join_loading = false;
            this.calculateSalarySingle(row);
          }
          if (type === 'quit') {
            row.is_quit_certain = !row.is_quit_certain;
            row.work_days_quit = response.date_count;
            row.quit_loading = false;
            this.calculateSalarySingle(row);
          }
        } else {
          this.$message.error("内部错误！错误原因：" + response.res_message);
          row.join_loading = false;
          row.quit_loading = false;
        }
      }).catch(err => {
        this.$message.error("调用错误！错误原因：" + err);
        row.join_loading = false;
        row.quit_loading = false;
      })
    },
    updateJoinDate(row) {
      row.is_join_certain = !row.is_join_certain;
    },
    updateQuitDate(row) {
      row.is_quit_certain = !row.is_quit_certain;
    },
    calculateSalary() {
      this.tableData.forEach((value, index) => {
        this.tableData[index].total_salary = this.tableData[index].monthly_salary;
        this.tableData[index].total_salary_log = this.tableData[index].monthly_salary + "(基础月工资) - "
            + this.tableData[index].personal_leave_day.length * this.tableData[index].monthly_salary + "(事假扣减) - "
            + this.tableData[index].sick_leave_day.length * this.tableData[index].monthly_salary + "(病假扣减) = "
            + this.tableData[index].total_salary + " 元"
      })
      this.$message({
        message: '导入成功，初始数据加载成功',
        type: 'success'
      });
    },
    calculateSalarySingle(value) {
      //当月事假扣减
      let personal_leave_discount = (value.personal_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2);
      //当月病假扣减
      let sick_leave_discount = (value.sick_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2);
      //初始化一下减掉病假+事假的工资以供后面处理
      value.monthly_salary = value.monthly_salary_default - personal_leave_discount - sick_leave_discount;
      // console.log(value.is_quit_certain);
      // console.log(value.is_quit_this_month);
      // console.log(value.quit_date.length);
      // console.log(value.is_join_certain);
      // console.log(value.is_join_certain);
      //当选择的是本月离职时
      if (value.is_quit_certain && value.is_quit_this_month && value.quit_date.length !== 0 && !value.is_join_this_month) {
        //当月工作工资（离职）
        value.monthly_salary = (value.monthly_salary / this.monthly_workdays * value.work_days_quit).toFixed(2);
        //总薪酬
        value.total_salary = (value.monthly_salary - personal_leave_discount - sick_leave_discount).toFixed(2);
        value.total_salary_log = value.monthly_salary + "(当月工作工资) -"
            + sick_leave_discount + "(病假扣减) -"
            + personal_leave_discount + "(事假扣减)"
            + "= " + value.total_salary + " 元"
      }

      //当选择的是本月入职时
      if (value.is_join_certain && value.is_join_this_month && value.join_date.length !== 0 && !value.is_quit_this_month) {
        //当月工作工资（入职）
        value.monthly_salary = (value.monthly_salary / this.monthly_workdays * value.work_days_join).toFixed(2);
        //总薪酬
        value.total_salary = (value.monthly_salary - personal_leave_discount - sick_leave_discount).toFixed(2)
        value.total_salary_log = value.monthly_salary + "(当月工作工资) -"
            + sick_leave_discount + "(病假扣减) -"
            + personal_leave_discount + "(事假扣减)"
            + "= " + value.total_salary + " 元"
      }

      if (!value.is_join_this_month && !value.is_quit_this_month) {
        //当月工资
        value.monthly_salary = value.monthly_salary_default;
        value.total_salary = (value.monthly_salary - personal_leave_discount - sick_leave_discount).toFixed(2);
        value.total_salary_log = value.monthly_salary + "(当月工作工资) -"
            + sick_leave_discount + "(病假扣减) -"
            + personal_leave_discount + "(事假扣减)"
            + "= " + value.total_salary + " 元"
      }
    },
    //修改了事病假时间时做的薪资计算
    dayChange(value) {
      value.total_salary = (value.monthly_salary
          - (value.sick_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2)
          - (value.personal_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2)).toFixed(2)
      value.total_salary_log = value.monthly_salary + "(基础月工资) - "
          + (value.personal_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2) + "(事假扣减) - "
          + (value.sick_leave_day.length * value.monthly_salary / this.monthly_workdays).toFixed(2) + "(病假扣减) "
          + "= " + value.total_salary + " 元"
    },
    handleChange(file) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (this.fileTemp.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
            this.fileTemp.type === "application/vnd.ms-excel") {
          this.importfxx(this.fileTemp)
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，只允许xlsx/xls格式文件，请删除后重新上传!"
          });
        }
      }
    },
    /** 格式化 */
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    /** 导出excel */
    exportExcel() {
      require.ensure([], () => {
        // 设置Excel的表格第一行的标题
        const tHeader = ['序号', '姓名', '初始月薪(税后)', '事假日期', '病假日期'
          , '是否当月入职', '入职时间', '是否当月离职', '离职时间', '实际月薪'
          , '累积应纳税所得额（截至上月）', '五险一金', '累积应纳税额（截止上月）'
          , '税前工资', '应纳税所得额（截止本月）', '累计应纳税额（截止本月）', '当月实际应交税额'];
        // tableData里对象的属性
        const filterVal = ['uid', 'name', 'monthly_salary_default', 'personal_leave_day', 'sick_leave_day'
          , 'is_join_this_month', 'join_date', 'is_quit_this_month', 'quit_date', 'total_salary'
          , 'salary_need_tax_last_month', 'wxyj', 'tax_paid_last_month'
          , 'salary_before_tax', 'salary_need_tax_this_month', 'tax_paid_this_month', 'tax_need_to_pay_this_month'];
        const list = this.tableData;  //把data里的tableData存到list
        const data = this.formatJson(filterVal, list);
        const date = format(new Date(), 'yyyyMMdd')
        export_json_to_excel(tHeader, data, "工资/税额信息-" + date);
      })
    },
    importfxx(obj) {
      this.$message({
        showClose: true,
        message: '文件正在导入...'
      });
      let _this = this;
      // 通过DOM取文件数据
      this.file = obj;
      let rABS = false; //是否将文件读取为二进制字符串
      let f = this.file;
      let reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        let binary = "";
        let rABS = false; //是否将文件读取为二进制字符串
        let wb; //读取完成的数据
        let outdata;
        let reader = new FileReader();
        reader.onload = function () {
          let bytes = new Uint8Array(reader.result);
          let length = bytes.byteLength;
          for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          let XLSX = require("xlsx");
          if (rABS) {
            // wb = XLSX.read(btoa(fixdata(binary)), {
            //   //手动转化
            //   type: "base64"
            // });
          } else {
            wb = XLSX.read(binary, {
              type: "binary"
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
          this.da = [...outdata];
          let arr = [];
          this.da.map((val, index) => {
            let obj = {};
            obj.uid = index + 1;
            obj.name = val["姓名"];
            //默认月薪
            obj.monthly_salary_default = val["到手月薪"];
            //实际月薪（初始情况下就是默认月薪）
            obj.monthly_salary = val["到手月薪"];
            obj.salary_need_tax_last_month = val["累积应纳税所得额（截至上月）"];
            obj.wxyj = val["五险一金"];
            obj.tax_paid_last_month = val["累积应纳税额（截止上月）"];
            obj.personal_leave_day = '';
            obj.sick_leave_day = '';
            obj.total_salary = '';
            obj.total_salary_log = '';
            obj.is_join_certain = false;
            obj.is_quit_certain = false;
            obj.is_quit_this_month = false;
            obj.is_join_this_month = false;
            obj.is_certain = false;
            obj.quit_date = '';
            obj.join_date = '';
            obj.work_days_join = '';
            obj.work_days_quit = '';
            obj.quit_loading = false;
            obj.join_loading = false;
            obj.salary_before_tax = '';
            obj.salary_need_tax_this_month = '';
            obj.tax_paid_this_month = '';
            obj.tax_need_to_pay_this_month = '';
            arr.push(obj);
          });
          _this.tableData = arr;
          _this.calculateSalary();

        };
        reader.readAsArrayBuffer(f);
      };

      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove() {
      this.fileTemp = null;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
          `当前限制选择1个文件，本次选择了 ${
              files.length
          } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
  }
}
</script>

<style scoped>
.FKLSalaryIndex {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}

#fkl_logo {
  padding-bottom: 30px;
}

.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #000000;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.margin-right-10 {
  margin-right: 10px;
}

.x-el-form-item-label >>> .el-form-item__label {
  color: #303133;
  font-weight: bold;
  font-size: 15px;
}
.cls-inline_block{
  display: inline-block;
}
</style>